package cn.itcast.hotel.utils;

import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.web.result.PageResult;
import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 分页结果解析工具类
 *
 * @Author XiaoJiangShi
 * @Date 2022/8/6 20:36
 * @Blog blog.XiaoJiangShi.net/996.mba
 * @Description: 分页结果解析工具类
 */
public class ResultUtil {

    /**
     * 对搜索响应数据进行解析处理
     *
     * @param response 搜索响应
     * @return 结果集对象
     */
    public static PageResult<HotelDoc> resultUtil(SearchResponse response) {
        List<HotelDoc> hotels = new ArrayList<>();
        PageResult<HotelDoc> result = new PageResult<>();
        long total = response.getHits().getTotalHits().value;

        SearchHit[] hits = response.getHits().getHits();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            //反序列化，把json转为对象
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            //获取高亮数值
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (highlightFields != null) {
                String name = highlightFields.get("name").toString();
                hotelDoc.setName(name);
            }

            //获取排序值
            Object[] sortValues = hit.getSortValues();
            if (sortValues.length > 0) {
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }
            hotels.add(hotelDoc);
        }
        result.setHotels(hotels);
        result.setTotal(total);
        return result;
    }

    /**
     * 根据聚合名称获取结果
     *
     * @param response 搜索后的响应
     * @param aggName  聚合名称
     * @return 返回结果集合
     */
    public static List<String> getAggListResult(SearchResponse response, String aggName) {
        List<String> list = new ArrayList<>();
        //获得aggregation对象
        Aggregations aggregations = response.getAggregations();
        //根据聚合名称获得terms对象
        Terms agg = aggregations.get(aggName);
        //获得bucket对象，是一个集合
        List<? extends Terms.Bucket> buckets = agg.getBuckets();
        //遍历，并得到每一个key，放入集合中
        for (Terms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            list.add(key);
        }
        //返回结果
        return list;
    }


}

